"""
    Created by 范钟<coder.zf@outlook.com> on 2019/04/07
"""
from sqlalchemy import Column, Integer, String, Boolean, Float
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

from app import login_manager
from models.base import Base


# flask_login 需要知道用户的ID，和其他一系列特殊的方法，
# 最好的办法是直接定义帮我们实现的方法， 特殊需要再覆盖， 具体方法需要查看 UserMixin
class User(Base, UserMixin):
    id = Column(Integer, primary_key=True, autoincrement=True)
    nickname = Column(String(64), nullable=False)
    phone_number = Column(String(18), unique=True)
    email = Column(String(64), unique=True)
    _password = Column('password', String(128), nullable=False)
    confirmed = Column(Boolean, default=False)
    beans = Column(Float, default=0)
    send_counter = Column(Integer, default=0)
    receive_counter = Column(Integer, default=0)
    wx_open_id = Column(String(64))
    wx_name = Column(String(32))

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw):
        return check_password_hash(self._password, raw)

    def get_id(self):
        # flask-login 插件要求必须定义这个方法
        return self.id


# 提供给flask查询用户信息
@login_manager.user_loader
def get_user(uid):
    return User.query.get(int(uid))
